package com.risetek.tft.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.risetek.tft.context.Constants;
import com.risetek.tft.context.SecurityLog;
import com.risetek.tft.entity.TManager;
import com.risetek.tft.entity.TMenu;
import com.risetek.tft.entity.TOperate;
import com.risetek.tft.entity.TOperateId;
import com.risetek.tft.service.ManagerService;
import com.risetek.tft.service.MenuService;
import com.risetek.tft.service.OperateService;
import com.zlinepay.common.upload.FileRepository;
import com.zlinepay.common.upload.UploadUtils;
import com.zlinepay.framework.bean.TreeNode;
import com.zlinepay.framework.web.util.CookieUtils;
import com.zlinepay.framework.web.util.RequestUtils;
import com.zlinepay.framework.web.util.ResponseUtils;


/**
 * @author ht
 *
 */
@Controller
public class IndexAction extends BaseAction{
	
	
	@Autowired
	private ManagerService managerService;
	@Autowired
	private MenuService menuService;
	@Autowired
	private OperateService operateService;
	/*@Autowired
	private DictService dictService;
 */
	@Autowired
	private FileRepository fileRepository;
	
	@RequestMapping("/right")
	public String right(HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		return "right";
	}
	
	@RequestMapping("/profile")
	public String profile(HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		
		return "profile";
	}
	

	@RequestMapping("/area")
	@ResponseBody
	public Map test(HttpServletResponse response) throws IOException{
		Map map = new HashMap ();
		map.put("f", 3);
		map.put("d", 2);
		return map; 
	}

	@RequestMapping("/main")
	public String index(HttpServletRequest request ,HttpServletResponse response,@RequestParam (defaultValue="0") String type , ModelMap model ){
		model.addAttribute("type", type);
		TManager manager = currentUser(request);
		List<TreeNode> list = menuService.listTree(manager);
		model.addAttribute("list", list);
		return "index";
	}
	
	
	@SecurityLog(descr = "", logOperate = "") 
	@RequestMapping("/op_{oper}_{id}")
	public String op(@PathVariable String oper, @PathVariable Integer id,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) {
		//id  菜单iD
		//oper  操作编号
		TManager account = currentUser(request);
		TOperateId operateId = new TOperateId(id, oper);
		TOperate operate = operateService.findById(operateId);
		//当前方法对应的菜单下面的操作对象 TOperate
		if (operate == null) {
			return noright(request, response, model);
		}
		boolean b = account.getIssuper();
		if(!b){
			if(oper.equals("save") || oper.equals("remove")){
				//不是超级管理员米有权限的
				return noright(request, response, model);
			}
		}
		model.addAttribute(Constants.OP_IN_REQUEST, operate);
		model.addAllAttributes(RequestUtils.getRequestMap(request));
		TMenu menu = operate.getTMenu();
		if ("list".equals(oper)) {
			String redirectURL = request.getRequestURI() + "?" + RequestUtils.getQueryString(request);
			//String redirectURL = RequestUtils.getURI(request) + "?" + RequestUtils.getQueryString(request);
			try {
				redirectURL = URLEncoder.encode(redirectURL, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			CookieUtils.addCookie(request, response, "_LAST_URL_", redirectURL, null);
			//TManager account = (TManager) request.getAttribute(Constants.USER_IN_REQUEST);
			Collection<TOperate> operates = null;
			if (account.getIssuper()) {
				operates = menu.getTOperates();
			} else {
				
				//核心  当前用户菜单下面有权限的所有操作 Collection<TOperate> operates 
				if (operateService.checkPermission(operateId, account.getManagerid())) {
					operates = operateService.getOperatesInPermissionByMenu( menu.getId(), account.getManagerid());
				} else {
					return noright(request, response, model);
				}
			}
			model.addAttribute("operates", operates);
			Map<String, String> map = RequestUtils.parseQueryString(menu.getParam());
			model.addAllAttributes(map);
			return menu.getChannel() + "/list";
			/*return "forward:" + menu.getChannel() + "/"
			+ operate.getId().getOp() + ".htm?"+menu.getParam();*/
		} else {
			Map<String, String> map = RequestUtils.parseQueryString(menu.getParam());
			model.addAllAttributes(map);
			return "forward:" + menu.getChannel() + "/"
					+ operate.getId().getOp() + "."+(StringUtils.isEmpty(cfg.get("suffix")) ? "action" : cfg.get("suffix"))+"?"+menu.getParam();
		}
	}
	 
	
	@RequestMapping(value = "/upload")
	public void upload(MultipartHttpServletRequest request,@RequestParam(value = "__source", required = false) MultipartFile file3, HttpServletResponse response,
			ModelMap model) throws IOException {
		Result result = new Result();
		String message = "";
		String error = "";
		String immediate = request.getParameter("immediate");
	//	MultipartFile file = request.getFile("__source");
		MultipartFile file = null;
		Map<String ,MultipartFile> file2 = request.getFileMap();
		String path = "";
		for(Map.Entry<String, MultipartFile> entry : file2.entrySet()) {
			 file = entry.getValue();
		}
		if (file == null || file.isEmpty()) {
			error = "文件太小！";
		} else {
			result.avatarUrls = new ArrayList();
			result.success = false;
			result.msg = "Failure!";
			String s = file.getOriginalFilename();
			boolean isSourcePic = file.getName().equals("__source");
			String fieldName = file.getName();
			
			if(file3 != null){
				isSourcePic = true;
				fieldName = file3.getOriginalFilename();
				file = file3;
			}
			File destFile = null;
			if ( fieldName.equals("__initParams") )
			{
				 
			}
			//如果是原始图片 file 域的名称或者以默认的头像域名称的部分“__avatar”打头(默认的头像域名称：__avatar1,2,3...，可在插件配置参数中自定义，参数名：avatar_field_names)
			else if ( isSourcePic || fieldName.startsWith("__avatar") )
			{
				
				//String virtualPath = "/upload/jsp_avatar" + avatarNumber + "_" + fileName + ".jpg";
				//原始图片（默认的 file 域的名称是__source，可在插件配置参数中自定义。参数名：src_field_name）。
				if( isSourcePic )
				{
					//文件名，如果是本地或网络图片为原始文件名、如果是摄像头拍照则为 *FromWebcam.jpg
					String sourceFileName = fieldName;	
					//原始文件的扩展名(不包含“.”)
					String sourceExtendName = sourceFileName.substring(sourceFileName.lastIndexOf('.') + 1);
					String filename = UploadUtils.generateFilename(sourceExtendName);
					path = "upload/files" + filename;
					result.sourceUrl =path;
				}
				//头像图片（默认的 file 域的名称：__avatar1,2,3...，可在插件配置参数中自定义，参数名：avatar_field_names）。
				else
				{
					String filename = UploadUtils.generateFilename("jpg");
					path = "upload/files" + filename;
					result.avatarUrls.add(request.getContextPath()+path);
				}
				
				destFile = fileRepository.storeByFilename(path, file);
				 
			}
			else
			{
				//注释① upload_url中传递的查询参数，如果定义的method为post请使用下面的代码，否则请删除或注释下面的代码块并使用注释②的代码
			/*	inputStream = new BufferedInputStream(fileItem.openStream());
				byte[] bytes = new byte [inputStream.available()];
				inputStream.read(bytes); 
				inputStream.close();
				if (fieldName.equals("userid"))
				{
					result.userid = new String(bytes, "UTF-8");
				}
				else if (fieldName.equals("username"))
				{
					result.username = new String(bytes, "UTF-8");
				}*/
			}
			
			/*String origName = file.getOriginalFilename();
			int index = origName.lastIndexOf(".");
			String title = index < 0 ? origName : origName.substring(0,
					index);
			String ext = FilenameUtils.getExtension(origName).toLowerCase(
					Locale.ENGLISH);
			File destFile = null;
			try {
				String filename = UploadUtils.generateFilename(ext);
				String path = "/upload/files" + filename;
				destFile = fileRepository.storeByFilename(path, file);
				if("1".equals(immediate)) {
					message = "!" + request.getContextPath()+path;
				} else {
					message = path;
				}
			} catch (Exception e) {
				error = "上传失败！";
				e.printStackTrace();
				if (destFile != null && destFile.exists()) {
					destFile.delete();
				}
			}*/
		}
		/*JSONObject obj = new JSONObject();
		obj.put("err", error);
		obj.put("msg", message);*/
		if ( result.sourceUrl != null )
		{
			//result.sourceUrl += initParams;
		}
		result.sourceUrl = request.getContextPath()+result.sourceUrl;
		result.success = true;
		result.msg = "Success!";
		/*
			To Do...可在此处处理储存事项
		*/
		
		TManager manager = (TManager) request.getAttribute(Constants.USER_IN_REQUEST);
		manager.setPhoto(path);
		this.managerService.update(manager);
		ResponseUtils.renderText(response, JSON.toJSONString(result));
	}
	
	
	
	
	/**
	 * 头像上传
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws FileUploadException  __source
	 */
	@RequestMapping("/upload2")
	public void upload(HttpServletRequest request2 ,HttpServletResponse response,MultipartHttpServletRequest request,@RequestParam(value = "__source", required = false) MultipartFile file3) throws IOException, FileUploadException{ 
		String contentType = request.getContentType();
		if ( contentType.indexOf("multipart/form-data") >= 0 )
		{
			Result result = new Result();
			result.avatarUrls = new ArrayList();
			result.success = false;
			result.msg = "Failure!";
			String userid;
			String username;
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			FileItemIterator fileItems = upload.getItemIterator(request);
			//定义一个变量用以储存当前头像的序号
			int avatarNumber = 1;
			//取服务器时间+8位随机码作为部分文件名，确保文件名无重复。
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssS"); 
			String fileName = simpleDateFormat.format(new Date());
			Random random = new Random();
			String randomCode = "";
			for ( int i = 0; i < 8; i++ )
			{
				randomCode += Integer.toString(random.nextInt(36), 36);
			}
			fileName = fileName + randomCode;
			//基于原图的初始化参数
			String initParams = "";
			BufferedInputStream	inputStream;
			BufferedOutputStream outputStream;
			//遍历表单域
			while( fileItems.hasNext() )
			{
				FileItemStream fileItem = fileItems.next();
				String fieldName = fileItem.getFieldName();
				//是否是原始图片 file 域的名称（默认的 file 域的名称是__source，可在插件配置参数中自定义。参数名：src_field_name）
				Boolean isSourcePic = fieldName.equals("__source");
				//当前头像基于原图的初始化参数（只有上传原图时才会发送该数据，且发送的方式为POST），用于修改头像时保证界面的视图跟保存头像时一致，提升用户体验度。
				//修改头像时设置默认加载的原图url为当前原图url+该参数即可，可直接附加到原图url中储存，不影响图片呈现。
				if ( fieldName.equals("__initParams") )
				{
					inputStream = new BufferedInputStream(fileItem.openStream());
					byte[] bytes = new byte [inputStream.available()];
					inputStream.read(bytes); 
					initParams = new String(bytes, "UTF-8");
					inputStream.close();
				}
				//如果是原始图片 file 域的名称或者以默认的头像域名称的部分“__avatar”打头(默认的头像域名称：__avatar1,2,3...，可在插件配置参数中自定义，参数名：avatar_field_names)
				else if ( isSourcePic || fieldName.startsWith("__avatar") )
				{
					String virtualPath = "/upload/jsp_avatar" + avatarNumber + "_" + fileName + ".jpg";
					//原始图片（默认的 file 域的名称是__source，可在插件配置参数中自定义。参数名：src_field_name）。
					if( isSourcePic )
					{
						//文件名，如果是本地或网络图片为原始文件名、如果是摄像头拍照则为 *FromWebcam.jpg
						String sourceFileName = fileItem.getName();	
						//原始文件的扩展名(不包含“.”)
						String sourceExtendName = sourceFileName.substring(sourceFileName.lastIndexOf('.') + 1);
						result.sourceUrl = virtualPath = String.format("/upload/jsp_source_%s.%s", fileName, sourceExtendName);
					}
					//头像图片（默认的 file 域的名称：__avatar1,2,3...，可在插件配置参数中自定义，参数名：avatar_field_names）。
					else
					{
						result.avatarUrls.add("/com.zlinepay"+virtualPath);
						avatarNumber++;
					}
					inputStream = new BufferedInputStream(fileItem.openStream()); 
					outputStream = new BufferedOutputStream(new FileOutputStream(request.getRealPath("/") + virtualPath.replace("/", "\\")));
					Streams.copy(inputStream, outputStream, true);
					inputStream.close();
		            outputStream.flush();
		            outputStream.close();
				}
				else
				{
					//注释① upload_url中传递的查询参数，如果定义的method为post请使用下面的代码，否则请删除或注释下面的代码块并使用注释②的代码
					inputStream = new BufferedInputStream(fileItem.openStream());
					byte[] bytes = new byte [inputStream.available()];
					inputStream.read(bytes); 
					inputStream.close();
					if (fieldName.equals("userid"))
					{
						result.userid = new String(bytes, "UTF-8");
					}
					else if (fieldName.equals("username"))
					{
						result.username = new String(bytes, "UTF-8");
					}
				}
			}
			//注释② upload_url中传递的查询参数，如果定义的method为get请使用下面注释的代码
			/*
			result.userid = request.getParameter("userid");
			result.username = request.getParameter("username");
			*/

			if ( result.sourceUrl != null )
			{
				result.sourceUrl += initParams;
			}
			result.sourceUrl = "/com.zlinepay"+result.sourceUrl;
			result.success = true;
			result.msg = "Success!";
			/*
				To Do...可在此处处理储存事项
			*/
			//返回图片的保存结果（返回内容为json字符串，可自行构造，该处使用fastjson构造）
			response.getWriter().print(JSON.toJSONString(result));
	}
		
		
	}
	
	
	/**
	* 表示上传的结果。
	*/
	private class Result
	{
		/**
		* 表示图片是否已上传成功。
		*/
		public Boolean success;
		public String userid;
		public String username;
		/**
		* 自定义的附加消息。
		*/
		public String msg;
		/**
		* 表示原始图片的保存地址。
		*/
		public String sourceUrl;
		/**
		* 表示所有头像图片的保存地址，该变量为一个数组。
		*/
		public ArrayList avatarUrls;
	}

}
